import React, { useEffect, useState } from 'react'
import { Button, Form, Input, message, Select } from 'antd';
import { Store } from 'antd/lib/form/interface';
import RichText from '../../components/richText';
import Editor from '../../components/editor';
import axios from '../../common/axios';
import { useHistory, useLocation } from 'react-router-dom';
import { ArticleData } from './index'
const formItemLayout = {
    labelCol: { span: 2 }
}
export interface Category {
    ID: number
    name: string
    order: number
}
const Add = () => {
    const history = useHistory();
    const location = useLocation();
    const [contentType, setContentType] = useState<'rich' | 'markdown'>('markdown');
    const [category, setCategory] = useState<Category[]>([]);
    const [content, setContent] = useState<string>('');
    const [detail, setDetail] = useState<ArticleData | string>();
    useEffect(() => {
        const query = new URLSearchParams(location.search);
        const id = query.get('id');
        if (id) {
            // 修改的
            (async () => {
                const { data }: { data: ArticleData } = await axios({
                    url: '/blog/article',
                    params: {
                        id
                    }
                })
                setContent(data.content);
                setDetail(data);
            })()
        } else {
            setDetail("ddasdsd")
        }
        (async () => {
            const { data }: { data: Category[] } = await axios({
                url: '/blog/category'
            })
            setCategory(data)
        })()
    }, [location.search])
    const onFinish = async (values: Store) => {
        console.log('Success:', values);
        if (detail && typeof detail !== 'string') {
            // 修改的
            values.ID = detail.ID
            if (contentType === 'markdown') {
                values.contentType = 1
            } else {
                values.contentType = 0
            }
            await axios({
                url: '/blog/article',
                method: 'put',
                data: values
            })
            message.success('修改成功');
        } else {
            await axios({
                url: '/blog/article',
                method: 'post',
                data: values
            })

            message.success('添加成功');
        }

        history.push('/article');
    };
    const checkContent = () => {
        if (content?.length) {
            return Promise.resolve();
        }
        return Promise.reject('请填写内容');
    };
    return (
        <>
            <Button onClick={() => {
                setContentType(contentType === 'markdown' ? 'rich' : 'markdown')
            }}>切换 {contentType === 'markdown' ? '富文本' : 'Markdown'} 写文章</Button>
            {
                detail ? (
                    <Form
                        {...formItemLayout}
                        name="basic"
                        initialValues={typeof detail === 'string' ? {} : detail}
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="标题"
                            name="title"
                            rules={[{ required: true, message: '请输入标题' }]}
                        >
                            <Input />
                        </Form.Item>
                        {/* <Form.Item
                            label="描述"
                            name="description"
                            rules={[{ required: true, message: '请输入描述' }]}
                        >
                            <Input />
                        </Form.Item> */}
                        <Form.Item
                            label="分类"
                            name="category"
                            rules={[{ required: true, message: '请选择' }]}
                        >
                            <Select style={{ width: 120 }}>
                                {
                                    category.map(item => {
                                        return <Select.Option key={item.ID} value={item.ID}>{item.name}</Select.Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="内容"
                            name="content"
                            rules={[{ validator: checkContent }]}>
                            {
                                contentType === 'markdown' ? (
                                    <Editor value={content} onChange={(editorState) => {
                                        setContent(editorState);
                                    }} />
                                ) : (
                                        <RichText value={content} onChange={(editorState) => {
                                            setContent(editorState);
                                        }} />
                                    )
                            }
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit" >
                                提交
                </Button>
                        </Form.Item>
                    </Form>
                ) : null
            }
        </>
    );
};

export default Add